﻿package com.ld.hpfs.web.controller;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.common.utils.DoubleUtil;
import com.ld.hpfs.pojo.Invoice;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.service.DealService;
import com.ld.hpfs.service.HistoryService;
import com.ld.hpfs.service.SplitAndMergeService;
import com.ld.hpfs.web.interseptor.WebConstants;

@Controller
public class SplitAndMergeController {
	private static final Logger logger = LoggerFactory
			.getLogger(SplitAndMergeController.class);

	@Autowired
	private SplitAndMergeService splitAndMergeService;
	
	@Autowired
	private HistoryService historyService;
	


	/*
	 * 校验相同货物:超出最大限额,限制行
	 */
	@RequestMapping(value = "/checkMaxValue")
	public void checkMaxValue(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String idStr = (String) request.getParameter("idStr") == null ? null
				: (String) request.getParameter("idStr");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param.put("ids", idStr);
				param.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY)
								.toString());
				int ret = splitAndMergeService.checkMaxValue(param);
				result.put("resultcode", ret);
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * mergeGoods 合并相同货物
	 */
	@RequestMapping(value = "/mergeGoods")
	public void mergeGoods(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String idStr = (String) request.getParameter("idStr") == null ? null
				: (String) request.getParameter("idStr");

		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		List<HashMap<String, Object>> orderByCustName = new ArrayList<HashMap<String, Object>>();
		List<HashMap<String,Object>> lists = new ArrayList<HashMap<String,Object>>();
		response.setContentType("text/plain;charset=UTF-8");
		String[] id = idStr.split(",");	
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
//				param.put("ids", ""+idStr+"");
				param.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY)
								.toString());
				HashMap<String,Object> map= new HashMap<String,Object>();
				for(int i=0;i<id.length;i++){
					map=new HashMap<String,Object>();
					map.put("id", id[i]);
					lists.add(map);
				}
				param.put("list", lists);
				orderByCustName=splitAndMergeService.orderByCustName(param);

				StringBuffer strHeadIds = new  StringBuffer();
		    	String lastCustName = "";
		    	String lastTypeCode="";
		    	int spRetCode = 0;
		    	
			    for(int i=0;i<orderByCustName.size();i++)
			    {
			    	HashMap<String, Object> item = orderByCustName.get(i);
			    	if(i == 0)
			    	{
			    		lastCustName = item.get("cust_name_chn").toString();
			    		lastTypeCode = item.get("doc_type_code").toString();
			    		strHeadIds.append(item.get("id_head_id").toString());
			    		continue;
			    	}
			    
			    	if(lastCustName.equals(item.get("cust_name_chn").toString())&& lastTypeCode.equals(item.get("doc_type_code").toString()))
			    	{
			    		if(strHeadIds.length() >0)
			    		{
			    			strHeadIds.append(",");
			    		}
			    		strHeadIds.append(item.get("id_head_id").toString());
			    	}
			    	else
			    	{
						param.put("ids", strHeadIds.toString());
						spRetCode = splitAndMergeService.mergeGoods(param);
						strHeadIds = new StringBuffer();
						strHeadIds.append(item.get("id_head_id").toString());
						lastCustName = item.get("cust_name_chn").toString();	
						lastTypeCode = item.get("doc_type_code").toString();
						if(spRetCode != 0)
						{
							break;
						}
			    	}
			    }
			    
			    if(spRetCode == 0 && strHeadIds.length() > 0)
			    {
					param.put("ids", strHeadIds.toString());
					spRetCode = splitAndMergeService.mergeGoods(param);
			    }
			    
				result.put("resultcode", spRetCode);
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * mergeClients 合并相同客户
	 */
	@RequestMapping(value = "/mergeClients")
	public void mergeClients(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String idStr = (String) request.getParameter("idStr") == null ? null
				: (String) request.getParameter("idStr");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
//		List<HashMap<String, Object>> orderByCustName = new ArrayList<HashMap<String, Object>>();
//		List<HashMap<String,Object>> lists = new ArrayList<HashMap<String,Object>>();
		response.setContentType("text/plain;charset=UTF-8");
//		String[] id = idStr.split(",");	
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
 				param.put("ids", ""+idStr+"");
				param.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY)
								.toString());
//				HashMap<String,Object> map= new HashMap<String,Object>();
//				for(int i=0;i<id.length;i++){
//					map=new HashMap<String,Object>();
//					map.put("id", id[i]);
//					lists.add(map);
//				}
//				param.put("list", lists);
//				orderByCustName=splitAndMergeService.orderByCustName(param);
//
//				StringBuffer strHeadIds = new  StringBuffer();
//		    	String lastCustName = "";
//		    	String lastTypeCode="";
		    	int spRetCode = 0;
		    	
//			    for(int i=0;i<orderByCustName.size();i++)
//			    {
//			    	HashMap<String, Object> item = orderByCustName.get(i);
//			    	if(i == 0)
//			    	{
//			    		lastCustName = item.get("cust_name_chn").toString();
//			    		lastTypeCode = item.get("doc_type_code").toString();
//			    		strHeadIds.append(item.get("id_head_id").toString());
//			    		continue;
//			    	}
//			    
//			    	if(lastCustName.equals(item.get("cust_name_chn").toString()) && lastTypeCode.equals(item.get("doc_type_code").toString()))
//			    	{
//			    		if(strHeadIds.length() > 0)
//			    		{
//			    			strHeadIds.append(",");
//			    		}
//			    		strHeadIds.append(item.get("id_head_id").toString());
//			    	}
//			    	else
//			    	{
//						param.put("ids", strHeadIds.toString());
		    			
						spRetCode = splitAndMergeService.mergeClients(param);
						
						// 用于添加履历
						if(spRetCode == 0){
							String[] ids = idStr.split(",");
							this.addHistory(ids, user, 3);
						}
						
//						strHeadIds = new StringBuffer();
//						strHeadIds.append(item.get("id_head_id").toString());
//						lastCustName = item.get("cust_name_chn").toString();
//						lastTypeCode = item.get("doc_type_code").toString();
//						if(spRetCode != 0)
//						{
//							break;
//						}
//			    	}
//			    }
			    
//			    if(spRetCode == 0 && strHeadIds.length() > 0)
//			    {
//					param.put("ids", strHeadIds.toString());
//					spRetCode = splitAndMergeService.mergeClients(param);
//			    }
			    
				result.put("resultcode", spRetCode);
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * splitAmount 拆分超最大金额
	 */
	@RequestMapping(value = "/splitAmount")
	public void splitAmount(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String id = (String) request.getParameter("id") == null ? null : (String) request.getParameter("id");
		boolean withTrialCalculation = request.getParameter("trial").equals("0") ? false: true;
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				// 此处拆分操作
				String[] ids = (String[]) id.split(",");
				List<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
				HashMap<String,String> hm = null;
				for(int i=0;i<ids.length;i++){
					hm = new HashMap<String, String>();
					hm.put("id", ids[i]);
					list.add(hm);
				}
				String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
				param.put("companyId", companyId);
				param.put("list", list);
				List<Invoice> invoice = (List<Invoice>) splitAndMergeService.getInvoiceById(param);
				if(invoice != null){
					
						result = splitAndMergeService.splitMaxAount(invoice,withTrialCalculation);
					
					
					// 用于添加履历
					if(result.get("result").toString().equals("success")){
						try{
							this.addHistory(ids,user, 2);
						}catch(Exception e){
							System.out.println(e);
						}
					}
					
				}
			} 
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e.getMessage());
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * splitDetailLine拆分超最大明细行
	 */
	@RequestMapping(value = "/splitDetailLine")
	public void splitDetailLine(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		String id = (String) request.getParameter("id") == null ? null
				: (String) request.getParameter("id");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {//批量处理 2013.05.13
				int ret = -1;
				String[] ids = (String[]) id.split(",");
				for(int i=0;i<ids.length;i++){
					param.put("id", ids[i]);
					param.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY)
								.toString());
				     ret = splitAndMergeService.splitDetailLine(param);
				}
				
				// 用于添加履历
				if(ret == 0){
					this.addHistory(ids,user, 2);
				}
				
				result.put("resultcode", ret);
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * splitManual手工拆分
	 * 2013.5.14  guxiaoli
	 */
	@RequestMapping(value = "/splitManual")
	public void splitManual(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String headId = (String) request.getParameter("headId") == null ? null
				: (String) request.getParameter("headId");
		String docNo = (String) request.getParameter("docNo") == null ? null
				: (String) request.getParameter("docNo");
		String groupArr = (String) request.getParameter("groupArr") == null ? null
				: (String) request.getParameter("groupArr");
		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param.put("headId", headId);
				param.put("docNo", docNo);				
				param.put("companyId",session.getAttribute(WebConstants.CURRENT_COMPANY)
						.toString());
				param.put("creator_id", user.getUserId());
				param.put("creator_name", user.getAccount());
				//更新update_id,update_name信息 by guxiaoli
				param.put("update_id", Integer.parseInt(user.getUserId()));
				param.put("update_name", user.getAccount());
				int ret = -1;
				@SuppressWarnings("unchecked")
				HashMap<String,Object> groupHash = JackJson.fromJsonToObject(groupArr, HashMap.class);				
				if(!groupHash.isEmpty()){
					ArrayList[] groupList = (ArrayList[])groupHash.values().toArray(new ArrayList[0]);
					for(Integer j = 0 ; j<groupList.length; j++){//判断拆分后单据长度是否超过20为若超过则不予保存
//						int aaa = (docNo+"_S"+Integer.toString(j+1)).length();
						if((docNo+"_S"+Integer.toString(j+1)).length()>20){
							ret = 1;
							break;
						}
					}
					if(ret != 1){
						for(Integer i = 0 ; i<groupList.length; i++){
							ArrayList list = groupList[i];
							param.put("list", list);
							param.put("newDocNo", docNo+"_S"+Integer.toString(i+1));
							param.put("Lines", list.size());
							Double ManualX;
							Double totalAmount = 0.0;
							Double totalTax = 0.0;
							for(Integer j = 0;j<list.size();j++){
								@SuppressWarnings("unchecked")
								HashMap<String,Object> temp = (HashMap<String,Object>)list.get(j);
								if(Integer.parseInt(temp.get("PRICE_WAY").toString()) == 0){
									ManualX=1.0;
				            	}else{
				            		ManualX = 1 + Double.parseDouble(temp.get("TAX_RATE").toString());
								}
								Double A = Double.parseDouble(temp.get("PRICE_CUR").toString())*Double.parseDouble(temp.get("QUANTITY").toString());
								Double DA = A*Double.parseDouble(temp.get("DISCOUNT_RATE").toString());
								Double T = A*Double.parseDouble(temp.get("TAX_RATE").toString())/ManualX;
								Double DT = A*Double.parseDouble(temp.get("DISCOUNT_RATE").toString())*Double.parseDouble(temp.get("TAX_RATE").toString())/ManualX;
							    totalAmount += ((A-DA)/ManualX);
							    totalTax += (T-DT);
							}
							param.put("totalAmount", DoubleUtil.formatDigitDecimal(totalAmount,2));
							param.put("totalTax", DoubleUtil.formatDigitDecimal(totalTax,2));
							// 取得拆分之前的单据明细id和单据类型
							ArrayList<HashMap<String, Object>> ManualDetailId = splitAndMergeService.getManualDetailId(param);
							param.put("detailIdbefore", ManualDetailId.get(0).get("detailId"));
							if(ManualDetailId.size() == 1){
								param.put("type", ManualDetailId.get(0).get("type"));
							}else{
								param.put("type", ManualDetailId.get(i).get("type"));
							}
							ret = splitAndMergeService.saveSplitManual(param);
						}
					}
				}				
				if (ret == 0) {
					ret = splitAndMergeService.updateDocStateToSplit(param);
					
					// 用于添加履历
					if(ret == 0){
						String[] ids = {headId};
						this.addHistory(ids,user, 2);
					}
					
					if(ret == 0){
					    result.put("resultcode", 0);				
					}else{
						result.put("resultcode", 9);
					}
				}else if(ret == 1){
					result.put("resultcode", 1);
				} else {
					result.put("resultcode", 9);
				}
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 一键开票功能
	 * 2013/5/16  jason.lee
	 */
	@RequestMapping(value = "/dealQuickBill")
	public void quickMake(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer)
	{
		String idStr = (String)request.getParameter("idStr") == null ? null : (String)request.getParameter("idStr");
		String doc_type_code=(String)request.getParameter("doc_type_code")==null?null:(String)request.getParameter("doc_type_code");
		response.setContentType("text/plain;charset=UTF-8");
		String[] ids=idStr.split(",");
		HashMap<String,Object> result = new HashMap<String,Object>();
		HashMap<String,Object> param = new HashMap<String,Object>();
		List<HashMap<String,Object>> list=new ArrayList<HashMap<String,Object>>();
//		List<HashMap<String,Object>> BrotherId= new ArrayList<HashMap<String,Object>>();
		try
		{
			HashMap<String,Object> map= new HashMap<String,Object>();
			for(int i=0;i<ids.length;i++)
			{
				map= new HashMap<String,Object>();
				map.put("id", ids[i]);    
				list.add(map);
			}
			param.put("list", list);
			param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
			param.put("doc_type_code", doc_type_code);
			//更新update_id,update_name信息 by guxiaoli
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			param.put("update_id", Integer.parseInt(user.getUserId()));
			param.put("update_name", user.getAccount());
			
			//TAX_C_DOC_OPTIONS中得到ONE_TOUCH_MAKE
			String oneTouchMakes= splitAndMergeService.getOneTouchMake(param);
			String[] otm=oneTouchMakes.split(",");
//			String test=otm[0];
			int spRetCode = 0;
			for(int j=0;j<otm.length;j++)
			{
				
				if(otm[j].equals("MG"))      //进行合并相同货物操作
				{
					List<HashMap<String, Object>> orderByCustName = new ArrayList<HashMap<String, Object>>();
					List<HashMap<String,Object>> BrotherDoc= new ArrayList<HashMap<String,Object>>();
					List<HashMap<String,Object>> BrotherId= new ArrayList<HashMap<String,Object>>();
					orderByCustName=splitAndMergeService.orderByCustName(param);

					StringBuffer strHeadIds = new  StringBuffer();
			    	String lastCustName = "";
			    	String lastTypeCode="";
//			    	int spRetCode = 0;
			    	
				    for(int i=0;i<orderByCustName.size();i++)
				    {
				    	HashMap<String, Object> item = orderByCustName.get(i);
				    	if(i == 0)
				    	{
				    		lastCustName = item.get("cust_name_chn").toString();
				    		lastTypeCode = item.get("doc_type_code").toString();
				    		strHeadIds.append(item.get("id_head_id").toString());
				    		continue;
				    	}
				    
				    	if(lastCustName.equals(item.get("cust_name_chn").toString())&& lastTypeCode.equals(item.get("doc_type_code").toString()))
				    	{
				    		if(strHeadIds.length() >0)
				    		{
				    			strHeadIds.append(",");
				    		}
				    		strHeadIds.append(item.get("id_head_id").toString());
				    	}
				    	else
				    	{
							param.put("ids", strHeadIds.toString());
							spRetCode = splitAndMergeService.mergeGoods(param);
							strHeadIds = new StringBuffer();
							strHeadIds.append(item.get("id_head_id").toString());
							lastCustName = item.get("cust_name_chn").toString();	
							lastTypeCode = item.get("doc_type_code").toString();
							if(spRetCode != 0)
							{
								break;
							}
				    	}
				    }
				    
				    if(spRetCode == 0 && strHeadIds.length() > 0)
				    {
						param.put("ids", strHeadIds.toString());
						spRetCode = splitAndMergeService.mergeGoods(param);
				    }
				    
					//TAX_R_DOC_REPRODUCE中得到生成后DOCUMENT_NO再得到ID_HEAD_ID放入PARAM中,以应付下面的1，2，3，4种情况
//				    BrotherDoc=splitAndMergeService.getBrotherDoc(param);
//				    if(BrotherDoc!=null && BrotherDoc.size()!=0)
//				    {
//				    	for(int q=0;q<BrotherDoc.size();q++)
//				    	{
//				    		HashMap<String, Object> item =BrotherDoc.get(q);
//				    		String doc=item.get("document_no").toString();
//				    		HashMap<String,Object> mapDoc=new HashMap<String,Object>();
//				    		mapDoc.put("doc", doc);
//				    		list.add(mapDoc);
//				    	}
//				    	param.put("list", list);
//				    }
					BrotherId=splitAndMergeService.getBrotherId(param);
					if(BrotherId!=null &&BrotherId.size()!=0)
					 {
						list.clear();
						for(int p=0;p<BrotherId.size();p++)
						{
							
							HashMap<String, Object> item =BrotherId.get(p);
							int id=Integer.parseInt(item.get("id_head_id").toString());
							HashMap<String,Object> map1=new HashMap<String,Object>();
							map1.put("id", id);
							
							list.add(map1);
						}
						param.clear();
						param.put("list", list);
						param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
					 }
				    
				}
				if(otm[j].equals("MC"))        //进行合并相同客户操作
				{
					List<HashMap<String, Object>> orderByCustName = new ArrayList<HashMap<String, Object>>();
					List<HashMap<String,Object>> BrotherDoc= new ArrayList<HashMap<String,Object>>();
					List<HashMap<String,Object>> BrotherId= new ArrayList<HashMap<String,Object>>();
					orderByCustName=splitAndMergeService.orderByCustName(param);

					StringBuffer strHeadIds = new  StringBuffer();
			    	String lastCustName = "";
			    	String lastTypeCode="";
//			    	int spRetCode = 0;
			    	
				    for(int i=0;i<orderByCustName.size();i++)
				    {
				    	HashMap<String, Object> item = orderByCustName.get(i);
				    	if(i == 0)
				    	{
				    		lastCustName = item.get("cust_name_chn").toString();
				    		lastTypeCode = item.get("doc_type_code").toString();
				    		strHeadIds.append(item.get("id_head_id").toString());
				    		continue;
				    	}
				    
				    	if(lastCustName.equals(item.get("cust_name_chn").toString()) && lastTypeCode.equals(item.get("doc_type_code").toString()))
				    	{
				    		if(strHeadIds.length() > 0)
				    		{
				    			strHeadIds.append(",");
				    		}
				    		strHeadIds.append(item.get("id_head_id").toString());
				    	}
				    	else
				    	{
							param.put("ids", strHeadIds.toString());
							spRetCode = splitAndMergeService.mergeClients(param);
							strHeadIds = new StringBuffer();
							strHeadIds.append(item.get("id_head_id").toString());
							lastCustName = item.get("cust_name_chn").toString();
							lastTypeCode = item.get("doc_type_code").toString();
							if(spRetCode != 0)
							{
								break;
							}
				    	}
				    }
				    
				    if(spRetCode == 0 && strHeadIds.length() > 0)
				    {
						param.put("ids", strHeadIds.toString());
						spRetCode = splitAndMergeService.mergeClients(param);
				    }
				  //TAX_R_DOC_REPRODUCE中得到生成后DOCUMENT_NO再得到ID_HEAD_ID放入PARAM中,以应付下面的1，2，3，4种情况
		
					BrotherId=splitAndMergeService.getBrotherId(param);
					if(BrotherId!=null &&BrotherId.size()!=0)
					 {
						list.clear();
						for(int p=0;p<BrotherId.size();p++)
						{
							
							HashMap<String, Object> item =BrotherId.get(p);
							int id=Integer.parseInt(item.get("id_head_id").toString());
							HashMap<String,Object> map1=new HashMap<String,Object>();
							map1.put("id", id);
							
							list.add(map1);
						}
						param.clear();
						param.put("list", list);
						param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
					 }
				}
				if(otm[j].equals("SD"))     //进行拆分明细的操作
				{
//					int spRetCode = 0;
					ArrayList str= (ArrayList) param.get("list");
					for(int i=0;i<str.size();i++)
					{
						HashMap<String, Object> s= (HashMap<String, Object>) str.get(i);
					
						param.put("id", s.get("id"));
					spRetCode = splitAndMergeService.splitDetailLine(param);
			
					}
					List<HashMap<String,Object>> BrotherDoc= new ArrayList<HashMap<String,Object>>();
					
					  //TAX_R_DOC_REPRODUCE中得到生成后DOCUMENT_NO再得到ID_HEAD_ID放入PARAM中,以应付下面的1，2，3，4种情况
			
				List<HashMap<String,Object>> BrotherId= new ArrayList<HashMap<String,Object>>();
					BrotherId=splitAndMergeService.getBrotherId(param);
					if(BrotherId!=null &&BrotherId.size()!=0)
					 {
						list.clear();
						for(int p=0;p<BrotherId.size();p++)
						{
							
							HashMap<String, Object> item =BrotherId.get(p);
							int id=Integer.parseInt(item.get("id_head_id").toString());
							HashMap<String,Object> map1=new HashMap<String,Object>();
							map1.put("id", id);
							
							list.add(map1);
						}
						param.clear();
						param.put("list", list);
						param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
					 }
				}
				if(otm[j].equals("SA"))     //进行拆分超额操作
				{
					String spRet = "";
					List<HashMap<String,Object>> BrotherDoc= new ArrayList<HashMap<String,Object>>();
					List<HashMap<String,Object>> BrotherId= new ArrayList<HashMap<String,Object>>();
					List<Invoice> invoice = (List<Invoice>) splitAndMergeService.getInvoiceById(param);
					HashMap<String, Object> message = new HashMap<String, Object>();
					if(invoice != null){
						message = splitAndMergeService.splitMaxAount(invoice,false);
						if(message.get("result").equals(""))
						{
							spRetCode = 0;
						}
					}
					  //TAX_R_DOC_REPRODUCE中得到生成后DOCUMENT_NO再得到ID_HEAD_ID放入PARAM中,以应付下面的1，2，3，4种情况
					BrotherId=splitAndMergeService.getBrotherId(param);
					if(BrotherId!=null &&BrotherId.size()!=0)
					 {
						list.clear();
						for(int p=0;p<BrotherId.size();p++)
						{
							
							HashMap<String, Object> item =BrotherId.get(p);
							int id=Integer.parseInt(item.get("id_head_id").toString());
							HashMap<String,Object> map1=new HashMap<String,Object>();
							map1.put("id", id);
							
							list.add(map1);
						}
						param.clear();
						param.put("list", list);
						param.put("companyId", session.getAttribute(WebConstants.CURRENT_COMPANY).toString());
					 }
				}
			
			}
			splitAndMergeService.setAuditedVoucher(param);
			
			if(spRetCode == 0){
				this.addHistory(ids, user, 1);
			}
			
			result.put("resultcode", spRetCode);
		
			writer.print(JackJson.fromObjectToJson(result));
		}
		catch(Exception e)
		{
			logger.error("Exception:",e);
		}
		 finally {
				writer.flush();
				writer.close();
			}
	}


	/*
	 * mergePostAndNegative合并正负数
	 * 2013.05.17  BY guxiaoli 
	 */
	@RequestMapping(value = "/mergePostAndNegative")
	public void mergePostAndNegative(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String idA = (String)request.getParameter("idA") == null ? null
				: (String) request.getParameter("idA");
		String idB = (String)request.getParameter("idB") == null ? null
				: (String) request.getParameter("idB");

		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY)
								.toString());
				param.put("idA", idA);
				param.put("idB", idB);
				int ret = splitAndMergeService.mergePostAndNegative(param);	
				
				// 用于添加履历
				if(ret == 0){
					String[] ids = {idA, idB};
					this.addHistory(ids,user, 3);
				}
				
				result.put("resultcode", ret);
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/*
	 * generateDiscount生成折扣
	 * 2013.05.17  BY guxiaoli 
	 */
	@RequestMapping(value = "/generateDiscount")
	public void generateDiscount(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String idA = (String)request.getParameter("idA") == null ? null
				: (String) request.getParameter("idA");
		String idB = (String)request.getParameter("idB") == null ? null
				: (String) request.getParameter("idB");

		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {
				param.put("companyId",
						session.getAttribute(WebConstants.CURRENT_COMPANY)
								.toString());
				param.put("idA", idA);
				param.put("idB", idB);
				int ret = splitAndMergeService.generateDiscount(param);	
				
				// 用于添加履历
				if (ret == 0){
					String[] ids = {idA, idB};
					this.addHistory(ids,user, 3);
				}
				
				result.put("resultcode", ret);
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	

	/*
	 * mergeDetails合并明细行
	 * 2013.05.24  BY guxiaoli
	 */
	@RequestMapping(value = "/mergeDetails")
	public void mergeDetails(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String idStr = (String)request.getParameter("idStr") == null ? null
				: (String) request.getParameter("idStr");
		String quantityVal = (String)request.getParameter("quantityVal") == null ? null
				: (String) request.getParameter("quantityVal");
		String priceVal = (String)request.getParameter("priceVal") == null ? null
				: (String) request.getParameter("priceVal");
		String nameVal = (String)request.getParameter("nameVal") == null ? null
				: (String) request.getParameter("nameVal");
		String specVal = (String)request.getParameter("specVal") == null ? null
				: (String) request.getParameter("specVal");
		String unitVal = (String)request.getParameter("unitVal") == null ? null
				: (String) request.getParameter("unitVal");
		String itemVal = (String)request.getParameter("itemVal") == null ? null
				: (String) request.getParameter("itemVal");
		String disrateVal = (String)request.getParameter("disrateVal") == null ? null
				: (String) request.getParameter("disrateVal");
		String quantityIn = (String)request.getParameter("quantityIn") == null ? null
				: (String) request.getParameter("quantityIn");
		String priceIn = (String)request.getParameter("priceIn") == null ? null
				: (String) request.getParameter("priceIn");
		String nameIn = (String)request.getParameter("nameIn") == null ? null
				: (String) request.getParameter("nameIn");
		String specIn = (String)request.getParameter("specIn") == null ? null
				: (String) request.getParameter("specIn");
		String unitIn = (String)request.getParameter("unitIn") == null ? null
				: (String) request.getParameter("unitIn");
		String itemIn = (String)request.getParameter("itemIn") == null ? null
				: (String) request.getParameter("itemIn");

		HashMap<String, Object> result = new HashMap<String, Object>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			if (user != null) {				
				String companyId = session.getAttribute(WebConstants.CURRENT_COMPANY).toString();
				param.put("idx", idStr);
				param.put("cpn_id", companyId);
				param.put("quantity", quantityVal);
				param.put("price_cur", priceVal);
				param.put("goods_name", nameVal);
				param.put("spec", specVal);
				param.put("goods_unit", unitVal);
				param.put("tax_item", itemVal);
				param.put("discount_rate", disrateVal);
				param.put("quantity_val", quantityIn);
				param.put("price_cur_val", priceIn);
				param.put("goods_name_val", nameIn);
				param.put("spec_val", specIn);
				param.put("goods_unit_val", unitIn);
				param.put("tax_item_val", itemIn);
				int ret = splitAndMergeService.mergeDetails(param);	
				
				System.out.println(idStr);
				// 用于添加履历
				if(ret == 0){
					String headStr = (String)request.getParameter("headIdStr") == null ? null
							: (String) request.getParameter("headIdStr");
					String[] ids = headStr.split(",");
					this.addHistory(ids,user, 3);
				}
				
				result.put("resultcode", ret);
			} else {
				result.put("resultcode", 9);
			}
			writer.print(JackJson.fromObjectToJson(result));
		} catch (Exception e) {
			logger.error("Exception:", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 添加合并、拆分履历
	 * @param ids 所有有可能被拆分、合并的原始票据内部编号
	 * @param user 当前用户
	 * @param action 1为一键开票，2为拆分，3为合并
	 */
	private void addHistory(String[] ids, User user, int action){
		// 一键开票、合并时
		if(action == 1 || action == 3){
			HashMap<Integer, ArrayList<Integer>> mergeInfo = historyService.getSplitMergeInfo(ids, false);
			if(mergeInfo != null){
				for(int child : mergeInfo.keySet()){
					HashMap<String, Object> hist_param = new HashMap<String ,Object>();
					hist_param.put("uid", Integer.parseInt(user.getUserId()));
				    	hist_param.put("uname", user.getAccount());
					// 添加变更后单据（merge后得到的单个单据）到履历动作表并备份变更后单据
					ArrayList<Integer> headIds = new ArrayList<Integer>();
					headIds.add(child);
					hist_param.put("headIds", headIds);
					int histId = historyService.addInvoiceHeadHistory(hist_param, 3, true);
					// 获得履历编号后，备份变更前单据（merge前的多个单据）到履历表
					hist_param.put("histId", histId);
					hist_param.put("headIds", mergeInfo.get(child));
					historyService.addInvoiceHeadHistory(hist_param, 3, false);
				}
			}
		}
		
		// 一键开票、拆分时
		if(action == 1 || action == 2){
			HashMap<Integer, ArrayList<Integer>> splitInfo = historyService.getSplitMergeInfo(ids, true);
			if(splitInfo != null){
				for(int parent : splitInfo.keySet()){
					HashMap<String, Object> hist_param = new HashMap<String ,Object>();
					hist_param.put("uid", Integer.parseInt(user.getUserId()));
				    	hist_param.put("uname", user.getAccount());
					// 添加变更后单据（split后得到的多个单据）到履历动作表并备份变更后单据
				    	hist_param.put("headIds", splitInfo.get(parent));
					int histId = historyService.addInvoiceHeadHistory(hist_param, 2, true);
					// 获得履历编号后，备份变更前单据（split前的多个单据）到履历表
					hist_param.put("histId", histId);
					ArrayList<Integer> headIds = new ArrayList<Integer>();
					headIds.add(parent);
					hist_param.put("headIds", headIds);
					historyService.addInvoiceHeadHistory(hist_param, 2, false);
				}
			}
		}
		// 一键开票时还需继续找到新票据是否再次进行了拆分、合并
		if(action == 1){
			String[] children = historyService.getChildrenByHeadId(ids);
			if(children.length > 0){
				this.addHistory(children, user, 1);
			}
		}
	}
}
